import 'dart:async';
import 'dart:convert';

import 'package:chathouse/model/member_info.dart';
import 'package:chathouse/pages/expert/buyWallet/recharge_bank_card.dart';
import 'package:chathouse/pages/route_manager/root_route_manager.dart';
import 'package:chathouse/public/Config.dart';
import 'package:chathouse/public/event_bus.dart';
import 'package:chathouse/util/base_utils.dart';
import 'package:chathouse/util/log.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:image_picker/image_picker.dart';

import '../../../constant/app_constant.dart';
import '../../../widgets/my_drop_down_widget.dart';
import '../../../widgets/my_input_widget.dart';

///編輯個人檔案
class EditAccountPage extends StatefulWidget {
  const EditAccountPage({Key? key}) : super(key: key);

  @override
  State<EditAccountPage> createState() => _EditAccountPageState();
}

class _EditAccountPageState extends State<EditAccountPage>
    with NavigationHelper {
  String? imageUrl;

  MemberInfo? _memberInfo;
  TextEditingController companyController = TextEditingController();
  TextEditingController nameController = TextEditingController();

  TextEditingController phoneTextEditingController = TextEditingController();
  TextEditingController emailTextEditingController = TextEditingController();

  String areaSelectedValue = "0";
  List<MyDropDownBean> areas = [
    MyDropDownBean("0", "+852"),
    MyDropDownBean("1", "+86"),
  ];
  late StreamSubscription<bool> keyboardSubscription;
  bool keyboardVisible = false;

  @override
  void initState() {
    super.initState();
    Object? json = SpUtil.getObject2(AppConstant.memberInfo);
    if (json != null) {
      _memberInfo = MemberInfo.fromJson2(json);
      imageUrl = _memberInfo?.data?.memberImage;
      companyController.text = _memberInfo?.data?.membersCorporation ?? "";
      nameController.text = _memberInfo?.data?.membersName ?? "";
      emailTextEditingController.text = _memberInfo?.data?.membersEmail ?? "";
      String nameText = _memberInfo?.data?.membersPhone ?? "";
      String areaText = "";
      if (nameText.startsWith("852")) {
        areaSelectedValue = "0";
        areaText = "852";
      }
      if (nameText.startsWith("86")) {
        areaSelectedValue = "1";
        areaText = "86";
      }
      var newName = nameText.replaceFirst(areaText, "");
      phoneTextEditingController.text = newName;
      setState(() {});
      // Net.getInstance().setDio("PROXY 192.168.6.140:8888");
    }
    var keyboardVisibilityController = KeyboardVisibilityController();
    // Subscribe
    keyboardSubscription =
        keyboardVisibilityController.onChange.listen((bool visible) {
      // print('Keyboard visibility update. Is visible: $visible');
      keyboardVisible = visible;
    });
  }

  @override
  void dispose() {
    companyController.dispose();
    nameController.dispose();
    phoneTextEditingController.dispose();
    emailTextEditingController.dispose();
    keyboardSubscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var keyboardSize = MediaQuery.of(context).viewInsets.bottom;
    return Scaffold(
      resizeToAvoidBottomInset: false,
      // appBar: getAppBar(title: ""),
      appBar: AppBar(
        backgroundColor: Colors.white,
        shadowColor: Colors.transparent,
        leading: Icon(
          Icons.arrow_back_ios,
          size: 18.w,
          color: MyColors.gary_149149149,
        ).setOnClickListener(() {
          back();
          // back(backData: 1);
        }),
        centerTitle: true,
        title: Text(
          "編輯个人檔案",
          textAlign: TextAlign.center,
          style:
              getTextStyle(28.sp, color: Colors.black, fontType: FontType.MID),
        ),
      ),
      body: ListView(
        children: [
          Container(
                  margin: EdgeInsets.only(top: 24.w),
                  alignment: Alignment.center,
                  child: (imageUrl?.isNullOrEmpty ?? true)
                      ? ImageUtils.image(Res.expert_avatar,
                              width: 80.w, height: 80.w, radius: 40.w)
                          .setContainer(
                              margin: EdgeInsets.only(right: Styles.magin_24))
                      : ImageUtils.image(imageUrl ?? "",
                              imageType: ImageType.NETWORK,
                              fit: BoxFit.cover,
                              width: 80.w,
                              height: 80.w,
                              radius: 40.w)
                          .setContainer(
                              margin: EdgeInsets.only(right: Styles.magin_24)))
              .setOnClickListener(() {
            onAddImage();
          }),
          MyInputWidget(
            title: "聯絡人/公司名稱",
            textStyle: getTextStyle(18.sp, fontType: FontType.MID),
            controller: companyController,
          ).setContainer(margin: EdgeInsets.only(top: 12.w)),
          MyInputWidget(
            title: "稱呼",
            textStyle: getTextStyle(18.sp, fontType: FontType.MID),
            controller: nameController,
          ).setContainer(margin: EdgeInsets.only(top: 12.w)),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                "電話號碼",
                style: getTextStyle(18.sp,
                    color: Colors.black, fontType: FontType.MID),
              ).setContainer(margin: EdgeInsets.only(bottom: 4.w)),
              Row(
                children: [
                  MyDropDownWidget(areaSelectedValue, areas, (val) {
                    areaSelectedValue = val;
                    setState(() {
                      phoneTextEditingController.clear();
                    });
                  }).setContainer(width: 100.w),
                  Expanded(
                      child: MyInputWidget(
                    placeholder: "電話號碼",
                    controller: phoneTextEditingController,
                    keyboardType: TextInputType.number,
                    inputFormatters: [
                      FilteringTextInputFormatter.digitsOnly, // 只允许输入数字
                      LengthLimitingTextInputFormatter(
                          areaSelectedValue == "0" ? 8 : 11), // 限制长度为8位
                    ],
                  ).setContainer(margin: EdgeInsets.only(left: 6.w)))
                ],
              ),
            ],
          ).setContainer(margin: EdgeInsets.only(top: 20.w)),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                "電郵",
                style: getTextStyle(18.sp,
                    color: Colors.black, fontType: FontType.MID),
              ).setContainer(margin: EdgeInsets.only(bottom: 4.w)),
              MyInputWidget(
                leftIcon: Icon(
                  Icons.email_outlined,
                  size: 24.w,
                  color: MyColors.gary_155155155,
                ).setContainer(margin: EdgeInsets.only(right: 4.w)),
                placeholder: "電郵登入",
                controller: emailTextEditingController,
              ),
            ],
          ).setContainer(margin: EdgeInsets.only(top: 20.w)),
          SizedBox(
            height: 50.w,
          ),
          Row(
            //必须加Row 不加 会铺满宽度  无法指定宽度
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text("存儲", style: getTextStyle(20.sp, color: Colors.white))
                  .setContainer(
                height: 50.w,
                width: 150.w,
                decoration: BoxDecoration(
                    color: MyColors.green_6915761,
                    borderRadius: BorderRadius.circular(25.w)),
                alignment: Alignment.center,
              )
                  .setOnClickListener(() {
                onSave(isClickButton: true);
              }, isInkWell: true),
            ],
          ),
          SizedBox(
            height: keyboardVisible ? keyboardSize : 20.w,
          ),
        ],
      ).setContainer(padding: EdgeInsets.symmetric(horizontal: 32.w)),
    );
  }

  onAddImage() async {
    int type = await Get.bottomSheet(Container(
      width: 1.sw,
      height: 120.w,
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(8.w), topRight: Radius.circular(8.w))),
      child: Column(
        children: [
          Text(
            "從相冊中選取",
            style: getTextStyle(18.sp, color: Colors.black),
          )
              .setContainer(
                  width: double.infinity,
                  height: 60.w,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      border: Border(
                          bottom: BorderSide(
                              width: 1.0.w, color: MyColors.gary_149149149))))
              .setOnClickListener(() {
            // back(backData: 1);
            Get.back(result: 1);
          }),
          Expanded(
              child: Text(
            "取消",
            style: getTextStyle(18.sp, color: Colors.black),
          ).setContainer(alignment: Alignment.center).setOnClickListener(() {
            Get.back();
            // back();
          })),
        ],
      ),
    ));
    final ImagePicker picker = ImagePicker();
    final XFile? image = await picker.pickImage(
        source: type == 1 ? ImageSource.gallery : ImageSource.camera);
    var imgData = await image?.readAsBytes();
    if (imgData == null) {
      return;
    }
    if (imgData.isEmpty) {
      return;
    }
    Obj.showLoading();
    Map result;
    String? url;
    Apis.uploadFile(imgData, image?.name ?? "image.png")
        .then((response) => {
              Obj.dismissLoading(),
              debugPrint("upload=${response?.data.toString()}"),
              result = jsonDecode(response?.data ?? ""),
              url = result["url"],
              if (url != null)
                {
                  LogUtil.d(imageUrl),
                  setState(() {
                    imageUrl = url!;
                  }),
                },
              onSave(isClickButton: false)
            })
        .catchError((error) => {Obj.dismissLoading(), setState(() {})});
  }

  onSave({isClickButton}) {
    if (areaSelectedValue == "0") {
      if (phoneTextEditingController.text.length != 8) {
        ToastUtil.showToast("輸入的電話號碼不合法");
        return;
      }
    } else if (areaSelectedValue == "1") {
      if (phoneTextEditingController.text.length != 11) {
        ToastUtil.showToast("輸入的電話號碼不合法");
        return;
      }
    }

    Obj.showLoading();
    Apis.getMembersInfo().then((value) {
      var jsonData = value?.data;
      _memberInfo = MemberInfo.fromJson(jsonData);
      SpUtil.putObject(AppConstant.memberInfo, _memberInfo!);
      LogUtil.d("getMembersInfo success ");
      String area = areas
          .firstWhere((element) {
            return areaSelectedValue == element.value;
          })
          .name
          .substring(1);
      String membersPhone = phoneTextEditingController.text.isNotEmpty
          ? (area + phoneTextEditingController.text)
          : "";
      if (membersPhone.isNullOrEmpty) {
        ToastUtil.showToast("請輸入電話");
      }
      final params = {
        "memberImage": imageUrl ?? (_memberInfo?.data?.memberImage ?? ""),
        "membersCorporation": companyController.text, //	聯絡人/公司名稱
        "membersEmail": emailTextEditingController.text, //	会员邮箱
        "membersPhone": membersPhone, //会员电话
        "membersName": nameController.text, //m	会员名称
        "membersNo": _memberInfo?.data?.membersNo, //m	会员
        "membersId": "${_memberInfo?.data?.membersId}", //m	会
        "version": _memberInfo?.data?.version, //m	版本號
      };
      Apis.editMember(params).then((value) {
        Obj.dismissLoading();
        if (isClickButton) {
          back();
        }
        LogUtil.d("editMember successful......");
        ToastUtil.showToast("修改成功");
        eventBus.fire(UpdateClientAccountEvent());
      }).catchError((error) {
        LogUtil.d("editMember error $error");
        Obj.dismissLoading();
      });
    }).catchError((error) {
      Obj.dismissLoading();
      LogUtil.d("getMembersInfo error $error");
    });
  }
}
